import AMapLoader from '@amap/amap-jsapi-loader'
import '@amap/amap-jsapi-types'

import type {Ref} from 'vue'
import {onMounted, ref, shallowRef, watchEffect} from 'vue'

const VUE_APP_AMAP_KEY = 'e28af433d6fabd84d33509eca1a3efa3'
// const VUE_APP_AMAP_SECRET_KEY = 'd1243371803f635fdfa7b253ffb723e0'
// 加载地图API
function loadAMap() {
    const aMapLoaded = ref<boolean>(false)
    // 从环境变量读取AMAP KEY
    const key = VUE_APP_AMAP_KEY
    if (key) {
        onMounted(() => {
            AMapLoader.load({
                key,
                version: '2.0',
                plugins: [],
            }).then(() => {
                aMapLoaded.value = true
            })
        })
    } else {
        throw new Error('地图加载失败，API Key缺失.')
    }
    return aMapLoaded
}

// 初始化地图 ，传入作为容器的元素节点
export function useAMap(
    mapContainerRef: Ref<HTMLDivElement | undefined>,
    options?: any,
): Ref<AMap.Map | undefined> {
    const mapRef = shallowRef<AMap.Map>()
    const aMapLoaded = loadAMap()
    watchEffect(() => {
        if (aMapLoaded.value && mapContainerRef.value) {
            mapRef.value = new AMap.Map(mapContainerRef.value, options)
        }
    })
    return mapRef
}
